<template>
  <Layout>
    <Dividetb>
      <template #top>
        <TopBox title="备份与恢复">
          <FilterSearch
          ref="filterSearchRef"
            :placeholder="'请输入名称'"
            :searchCallBack="searchCallBack"
          />
          <topButtonGroup :buttonList="tbuttonList" />
          <!-- <div style="width: 200px"></div> -->
        </TopBox>
      </template>
      <template #bottom>
        <div class="tableBox">
          <el-table
            size="large"
            class="listTable"
            ref="backUPref"
            :data="tableData"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            align="center"
            height="80vh"
            table-layout="auto"
            v-loading="isLoading"
            @cell-mouse-enter="cellMouseEnter"
            @cell-mouse-leave="cellMouseLeave"
            @sort-change="handleSortChange"
            @selection-change="handleSelectionChange"
            @row-click="currentRowChange"
          >
            <el-table-column type="selection" width="55" size="large" />
            <el-table-column
              label="序号"
              type="index"
              width="60"
              :index="(index) => index + 1"
            />
            <el-table-column
              label="备份ID/备注信息"
              width="250"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                <div v-html="row.id" class="ellipse"></div>
              </template>
            </el-table-column>
            <el-table-column label="备份数据库" width="100">
              <template #default="{ row }">
                <div v-html="row.operationDatabase" class="ellipse"></div>
              </template>
            </el-table-column>
            <el-table-column label="备份文件">
              <template #default="{ row }">
                <div
                  v-html="row.backupFile"
                  style="width: 200px"
                  class="ellipse"
                  :title="htmlTotext(row.backupFile)"
                ></div>
              </template>
            </el-table-column>
            <el-table-column label="备份路径">
              <template #default="{ row }">
                <div
                  v-html="row.backupPath"
                  style="width: 200px"
                  class="ellipse"
                  :title="htmlTotext(row.backupPath)"
                ></div>
              </template>
            </el-table-column>
            <el-table-column prop="documentNumString" label="备份人">
              <template #default="{ row }">
                <span v-html="row.operationBy"></span>
              </template>
            </el-table-column>
            <el-table-column prop="operationTime" label="备份时间">
              <template #default="{ row }">
                <span>{{ getDayOfWeek(row.operationTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="还原时间">
              <template #default="{ row }">
                <span>{{ getDayOfWeek(row.restoreTime) ?? "暂无" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <!-- <div class="handle_box d-f jc-c ai-c">
                  <el-button
                    v-for="button in opebuttonList"
                    :key="button.label"
                    size="small"
                    link
                    @click.stop="button.onClick(scope.$index, scope.row)"
                  >
                    {{ button.label }}
                  </el-button>
                </div> -->
                <el-dropdown placement="bottom" popper-class="opeDropdown">
                  <el-button
                    link
                    size="small"
                    :icon="More"
                    class="moreBtn"
                    @click.stop="(e) => e.preventDefault()"
                  >
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu class="moreBtn_menu">
                      <el-dropdown-item
                        v-for="item in opebuttonList"
                        :key="item.label"
                        @click="item.onClick(scope.row)"
                      >
                        <el-button link :icon="item.icon" :type="item.type">
                          {{ item.label }}
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
            <template #append>
              <div class="load-tip">
                <span v-if="tableLoading">加载中...</span>
                <span v-else-if="!hasMore && tableData.length > 0"
                  >没有更多数据了</span
                >
              </div>
            </template>
          </el-table>
          <div class="page d-f jc-fe">
            总{{ total }}条数据
            <el-pagination
              v-model:current-page="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
              size="default"
              :disabled="disabled"
              :background="background"
              layout=" prev, pager, next, sizes"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :hide-on-single-page="hide"
            />
          </div>
        </div>

        <div
          id="tabinput"
          style="visibility: none; height: 0; overflow: hidden"
        >
          <input type="text" ref="tabinput" />
        </div>
      </template>
    </Dividetb>
  </Layout>
</template>
<script setup>
import { ref, toRaw, onMounted, reactive } from "vue";
import {
  More,
  FolderOpened,
  Top,
  EditPen,
  Delete,
} from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import NewWindow from "@/assets/customIcon/NewWindow.vue";
import WorkFlow from "@/assets/customIcon/WorkFlow.vue";
import MemberAssignment from "@/assets/customIcon/MemberAssignment.vue";
import useTagStore from "@/stores/tagList";
import Layout from "./layout.vue";
import Dividetb from "@/layout/components/dividetb.vue";
import TopBox from "@/components/TopTitleBox/index.vue";
import FilterSearch from "@/components/TopTitleBox/FilterSearch.vue";
import topButtonGroup from "@/components/ButtonGroup/topButtonGroup.vue";
import { cellMouseEnter, cellMouseLeave } from "@/utils/cellmouseEvent.js";
import { loading } from "@/utils/topButton.js";
import { getDayOfWeek } from "@/utils/timeChange.js";
import { htmlTotext } from "@/utils/getData.js";
import { downloadFile } from "@/utils/download";
import { parseTime } from "@/utils/common.js";
import {
  getBackupListData,
  backupSysData,
  delBackup,
  exportBackupList,
  restoreData,
} from "@/api/sys.js";
defineOptions({ name: "MyFolder" });
import router from "@/router";
const route = useRoute();
const tagStore = useTagStore();
const isLoading = ref(false);
const tableData = ref([]);
const tableLoading = ref(false);
const backUPref = ref(null);
const multiple = ref(true);
const curUser = ref("");
const once = ref(true);
const tbuttonList = ref([
  // {
  //   label: "回退",
  //   icon: "el-icon-back",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了回退");
  //     tagStore.historyBack({
  //       name: route.path,
  //       breadcrumbName: route.query.name || "文档",
  //     });
  //   },
  // },
  // {
  //   label: "前进",
  //   icon: "el-icon-right",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了我的文件夹");
  //     tagStore.historyFoward({
  //       name: `/document/l/myfolder`,
  //       breadcrumbName: "文档",
  //     });
  //   },
  // },
  {
    label: "手动系统备份",
    icon: "SysBackup",
    type: "b2",
    onClick: () => {
      console.log("点击了系统备份");
      backupSysData().then((res) => {
        if (res.code !== 200) return;
        ElMessage.success("系统备份成功!");
        regainData();
      });
    },
  },
  // {
  //   label: "导出数据库备份记录列表",
  //   icon: "exportIcon",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了导出");
  //     exportBackupList().then((res) => {
  //       console.log(res);
  //       downloadFile(
  //         res,
  //         "数据备份列表" +
  //           parseTime(new Date(), "{y}-{m}-{d} {h}:{i}") +
  //           ".xlsx"
  //       );
  //     });
  //   },
  // },
  {
    label: "刷新",
    icon: "el-icon-refresh",
    type: "b2",
    onClick: (e) => {
      console.log("点击了刷新");
      // 清空搜索条件
      delete filtrateFormData.params;
      filterSearchRef.value.reset();
      loading(e, () => {
        return new Promise((resolve) => {
          // 清空表格数据
          // tableData.value = [];
          isLoading.value = true;
          // 重新获取列表数据
          regainData().then(() => {
            isLoading.value = false;
            ElMessage.success("刷新成功");
            resolve();
          });
        });
      });
    },
  },
  {
    label: "批量删除",
    icon: "el-icon-delete",
    type: "b2",
    onClick: () => {
      if (selectedIds.value.length == 0) {
        ElMessage.warning("请选择要删除的备份记录");
        return;
      }
      console.log("点击了批量删除");
      ElMessageBox.confirm("确定要删除这些备份记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        icon: "WarnTriangleFilled",
        // icon: "warning",
        type: "warning",
      }).then(() => {
        delBackup(selectedIds.value.join(",")).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage.success("删除成功");
            // getMyFolderList();
            regainData();
          } else {
            ElMessage.error("删除失败");
          }
        });
      });
    },
  },
]);
const opebuttonList = [
  {
    icon: Top,
    label: "恢复",
    onClick: (row) => {
      // console.log("成员", row);
      restoreData(row.id).then((res) => {
        if (res.code !== 200) return;
        ElMessage.success("数据恢复成功!");
        regainData();
      });
    },
  },
  {
    icon: Delete,
    label: "删除",
    type: "danger",
    onClick: (row) => {
      delBackup(row.id).then(async (res) => {
        console.log(res);
        if (res.code !== 200) return;
        ElMessage.success("删除成功!");
        // 删除成功后，重新获取列表数据
        regainData();
      });
    },
  },
];
const pagination = reactive({
  pageSize: 20,
  pageNum: 1,
});
// 操作分页器
const total = ref(0);
const background = ref(false);
const disabled = ref(false);
const hide = ref(false);
const selectedIds = ref([]);
// 多选框选中数据
function handleSelectionChange(selection) {
  selectedIds.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
  if (selection.length == 1) {
    once.value = false;
  } else {
    once.value = true;
  }
}
const currentRowChange = (curRow) => {
  console.log(curRow);
  const flag = selectedIds.value.includes(curRow.id);
  backUPref.value.toggleRowSelection(curRow, !flag);
  curUser.value = curRow.userName;
};
/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  // filtrateData.value = {};
  filtrateData.value.orderByColumn = column.prop;
  filtrateData.value.isAsc = column.order;
  setCondition2();
}
// 排序触发
const setCondition2 = () => {
  loading.value = true;
  getBackupList();
};
const filtrateFormData = reactive({}); // 筛选条件
const hasMore = ref(true);
const filterSearchRef = ref(null);
const searchCallBack = (word, time) => {
  console.log("搜索回调", word, time);
};
const regainData = () => {
  pagination.pageNum = 1;
  hasMore.value = true;
  return getBackupList();
};
const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  pagination.pageSize = val;
  getBackupList({ pageSize: val, pageNum: pagination.pageNum });
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  pagination.pageNum = val;
  getBackupList({ pageSize: pagination.pageSize, pageNum: val });
};
const getBackupList = (data = {}) => {
  let params = {
    ...data,
    ...pagination,
    ...filtrateFormData,
  };
  return new Promise((resolve, reject) => {
    loading.value = true;
    getBackupListData(data)
      .then((res) => {
        if (res.code == 200) {
          console.log(res);
          tableData.value = res.rows;
          total.value = res.total;
          loading.value = false;
          resolve(res);
        }
      })
      .catch((err) => {
        loading.value = false;
        reject();
      });
  });
};
onMounted(() => {
  console.log("我的文件夹页面挂载完成");
  // 获取备份列表
  // 默认获取第一页的数据
  getBackupList({ pageSize: pagination.pageSize, pageNum: 1 });
});
</script>
<style lang="scss" scoped>
.tableBox {
  :deep(.cell) {
    display: flex;
    justify-content: center;
    font-size: var(--el-font-size-base);
    &:has(.folderName) {
      justify-content: start;
    }
    .ellipse {
      width: 100%;
      white-space: nowrap;
      word-break: break-all;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  :deep(.zhiding) {
    border-bottom: none !important;
  }
  .moreBtn {
    display: none;
    &.active {
      display: flex;
    }
  }
}
.opeDropdown {
  button {
    width: 100%;
    justify-content: start;
  }
  .moreBtn_menu {
    li.el-dropdown-menu__item {
      button {
        padding: 6px 16px;
      }
    }
  }
}
</style>
